const fs = require('node:fs')
const path = require('node:path')

// 通过 window 对象向渲染进程注入 nodejs 能力
window.services = {
  // 读文件
  readFile (file) {
    return fs.readFileSync(file, { encoding: 'utf-8' })
  },
  // 文本写入到下载目录
  writeTextFile (text) {
    return this.writeGeneratorFile(text, Date.now().toString() + '.txt')
  },

  async writeGeneratorFile(str, fileName) {
    // const filePath = path.join(window.utools.getPath('downloads'), fileName)
    // 调用 uTools 的 showOpenDialog 让用户选择文件夹
    const result =  window.utools.showOpenDialog({
      properties: ['openDirectory']
    });
    console.log(result, 'chooseDir')
    if (result.canceled) {
      // 用户取消选择，可根据需求处理，这里简单返回 null
      return null;
    }

    const selectedFolder = result.filePaths[0];
    const filePath = path.join(selectedFolder, fileName);
    fs.writeFileSync(filePath, str, { encoding: 'utf-8' })
    return filePath
  },
  // 图片写入到下载目录
  writeImageFile (base64Url) {
    const matchs = /^data:image\/([a-z]{1,20});base64,/i.exec(base64Url)
    if (!matchs) return
    const filePath = path.join(window.utools.getPath('downloads'), Date.now().toString() + '.' + matchs[1])
    fs.writeFileSync(filePath, base64Url.substring(matchs[0].length), { encoding: 'base64' })
    return filePath
  },
  getItem(key) {
    return JSON.parse(window.utools.dbStorage.getItem(key))
  },
  setItem(key, value) {
    return window.utools.dbStorage.setItem(key, JSON.stringify(value))
  }
}
